﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebSocketClientApp
{
    public class WebSocketClient3
    {
        private const string Uri = "ws://localhost:8080/";
        private ClientWebSocket _ws;
        private readonly CancellationTokenSource _cts;

        /// <summary>
        /// 定义搜索蓝牙设备委托
        /// </summary>
        public delegate void DeviceFindReplyChangedEvent(string msg);

        /// <summary>
        /// 搜索蓝牙事件
        /// </summary>
        public event DeviceFindReplyChangedEvent DeviceFindReplyChanged;
        public WebSocketClient3()
        {
            _cts = new CancellationTokenSource();
        }
        public async Task ConnectAsync()
        {
            _ws = new ClientWebSocket();
            await _ws.ConnectAsync(new Uri(Uri), CancellationToken.None);
            Console.WriteLine("WebSocket 客户端已连接");

            // Start receiving messages in the background
            _ = ReceiveMessagesAsync();
        }
        string my_temp_letf_str = "";
        string my_temp_right_str = "";
        private async Task ReceiveMessagesAsync()
        {
            byte[] buffer = new byte[1024 * 10]; // Larger buffer for message reception
            while (_ws.State == WebSocketState.Open && !_cts.Token.IsCancellationRequested)
            {
                try
                {
                    var result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), _cts.Token);
                    if (result.MessageType == WebSocketMessageType.Text)
                    {
                        string receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
                        
                        LogHelper.WriteLog("收到数据-》"+ receivedMessage);

                        JObject jsonObject = JObject.Parse(receivedMessage);
                        string commondValue = jsonObject["command"].ToString();
                        if (commondValue == CommondCode.find_device_reply.ToString())
                        {
                            DeviceFindReplyChanged(receivedMessage);

                        }
                        // You can also invoke an event or delegate to update UI here
                    }
                    else if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", _cts.Token);
                        break;
                    }
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("接收消息操作被取消。");
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"接收消息异常：{ex.Message}");
                    break;
                }
            }
        }

        public async Task SendMessageAsync(string message)
        {
            if (_ws != null && _ws.State == WebSocketState.Open)
            {
                byte[] buffer = Encoding.UTF8.GetBytes(message);
                await _ws.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
                Console.WriteLine("发送消息：" + message);
                LogHelper.WriteLog("发送消息：" + message);
            }
            else
            {
                Console.WriteLine("无法发送消息：WebSocket 客户端未连接或状态不正确");
                LogHelper.WriteLog("无法发送消息：WebSocket 客户端未连接或状态不正确");
            }
        }

        public async Task DisconnectAsync()
        {
            try
            {
                _cts.Cancel(); // Cancel any ongoing receive operations
                if (_ws != null && _ws.State == WebSocketState.Open)
                {
                    await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                    Console.WriteLine("WebSocket 客户端已断开连接");
                }
                _ws?.Dispose();
                _cts.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

        }
        /// <summary>
        /// 功能：获取客户端是否连接到服务端
        /// </summary>
        /// <returns></returns>
        public bool getClientStats()
        {
            try
            {
                if (_ws != null && _ws.State == WebSocketState.Open)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                return false;
            }
        }
    }
}
